﻿using Company.Core.Models;
using Company.Database.Base.Entities;
using Company.Database.Base.Repositories;
using Microsoft.AspNetCore.Mvc;

namespace Company.WebServer.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class HL7Controller
    {
        private ISourceRepository SourceRepository { get; }
        private IHL7MSHRepository HL7MSHRepository { get; }
        private IHL7OBRRepository HL7OBRRepository { get; }
        private IHL7OBXRepository HL7OBXRepository { get; }
        private  IHL7PIDRepository HL7PIDRepository { get; }
        public HL7Controller(
            ISourceRepository sourceRepository,
            IHL7MSHRepository hL7MSHRepository, 
            IHL7OBRRepository hL7OBRRepository,
            IHL7OBXRepository hL7OBXRepository, 
            IHL7PIDRepository hL7PIDRepository)
        {
            SourceRepository = sourceRepository;
            HL7MSHRepository = hL7MSHRepository;
            HL7OBRRepository = hL7OBRRepository;
            HL7OBXRepository = hL7OBXRepository;
            HL7PIDRepository = hL7PIDRepository;
        }
        [HttpPost]
        [Route("UploadAsync")]
        public async  Task<IActionResult> UploadAsync(HL7 data)
        {
            Result<HL7> result = new();
            if (data == null)
            {
                result.Success = false;
                result.Message = "没有数据";
                return new JsonResult(result);
            }
            if (data.Source == null ||
                data.HL7MSH == null ||
                data.HL7PID == null ||
                data.HL7OBR == null ||
                data.HL7OBXList == null)
            {
                result.Success = false;
                result.Message = "没有数据";
                return new JsonResult(result);
            }

            var success1 = await SourceRepository.InsertAsync(data.Source) > 0;
            var success2 = await HL7MSHRepository.InsertAsync(data.HL7MSH) > 0;
            var success3 = await HL7PIDRepository.InsertAsync(data.HL7PID) > 0;
            var success4 = await HL7OBRRepository.InsertAsync(data.HL7OBR) > 0;
            var success5 = await HL7OBXRepository.InsertAsync(data.HL7OBXList) > 0;
            if(success1 && success2 && success3 && success4 && success5)
            {
                result.Success = true;
                result.Message = "操作成功";
                result.Value = data;
            }
            return new JsonResult(result);
        }
    }
}
